﻿using DataProcessor;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;

var path = Console.ReadLine();
var dataReader = new DataReader(new(path!));

foreach (int sample in new[] { 1, 2 })
{
    foreach (int frequency in new[] { 50, 100 })
    {
        const int imageSize = 1000;
        using var image = new Image<Rgba32>(imageSize, imageSize);
        image.Mutate(c => c.Fill(Color.Wheat));

        var fourData = Enumerable.Range(1, 4)
            .Select(division => dataReader.Read(sample, frequency, division))
            .ToArray();

        var fourMax = fourData
            .Select(points => points.MaxBy(point => point.Ch2))
            .ToArray();

        PointF DataPointToDrawingPoint((double Ch1, double Ch2) data)
        {
            const double reduction = 0.92F;
            var x = (data.Ch1 / fourMax[3].Ch1 * reduction + 1) * imageSize / 2;
            var y = (-data.Ch2 / fourMax[3].Ch2 * reduction + 1) * imageSize / 2;
            return new PointF((float)x, (float)y);
        }

        image.Mutate(c => {
            var drawingPoints = from points in fourData
                                from point in points
                                select DataPointToDrawingPoint(point);
            foreach (var current in drawingPoints)
            {
                var ellipse = new EllipsePolygon(current, 2);
                _ = c.Fill(Color.Gray, ellipse);
            }
        });

        image.Mutate(c => {
            var previous = DataPointToDrawingPoint(fourMax[0]);
            _ = c.Fill(Color.Blue, new EllipsePolygon(previous, 5));

            foreach (var currentData in fourMax.Skip(1))
            {
                var current = DataPointToDrawingPoint(currentData);

                var ellipse = new EllipsePolygon(current, 5);
                _ = c.Fill(Color.Blue, ellipse);

                _ = c.DrawLines(Pens.Dash(Color.Blue, 2), previous, current);
                previous = current;
            }
        });

        image.SaveAsJpeg($"out-{sample}-{frequency}.jpeg");

        using var file = new StreamWriter($"out-{sample}-{frequency}.txt", false);
        foreach (var max in fourMax)
        {
            file.WriteLine(max);
        }
    }
}

